package com.luguangxing.Fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.codbking.calendar.CalendarDate;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.luguangxing.Activity.R;
import com.luguangxing.Activity.databinding.FragmentMessageBinding;
import com.luguangxing.Adapter.MessageAdapter;
import com.luguangxing.Bean.CostRecordStatus;
import com.luguangxing.Interface.OkSuccessInterface;
import com.luguangxing.Util.CommonUtils;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.XToastUtils;

import java.text.SimpleDateFormat;
import java.util.*;

import static com.luguangxing.Util.CommonUtils.OKJsonPost;

public class MessageFragment extends Fragment {
    private FragmentMessageBinding binding;
    private LinearLayoutManager linearLayoutManager;
    private MessageAdapter messageAdapter;
    private RefreshLayout refreshLayout;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentMessageBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        binding.recyclerviewMessage.setLayoutManager(linearLayoutManager = new LinearLayoutManager(getContext()));
        binding.tvTitle.setText(CommonUtils.getCurrentTime("yyyy-MM-dd"));

        binding.calendarDateView.setAdapter((convertView, parentView, calendarDate) -> {
            TextView textView;
            if (convertView == null) {
                convertView = LayoutInflater.from(parentView.getContext()).inflate(R.layout.adapter_calendar_item, null);
                ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(DensityUtils.dp2px(getContext(), 48), DensityUtils.dp2px(getContext(), 48));
                convertView.setLayoutParams(params);
            }
            textView = convertView.findViewById(R.id.tv_text);
            textView.setBackgroundResource(R.drawable.bg_calendar_ding_ding_item);
            textView.setText(String.valueOf(calendarDate.day));
            if (calendarDate.monthFlag != 0) {
                textView.setTextColor(0xFF9299A1);
            } else {
                textView.setTextColor(0xFFFFFFFF);
            }
            return convertView;
        });

        binding.calendarDateView.setOnCalendarSelectedListener((view, position, calendarDate) -> listByDay(calendarDate));

        binding.calendarDateView.setOnMonthChangedListener((view, postion, date) -> listByMonth(date));

        refreshLayout = binding.refreshLayout;
        // 开启自动加载功能（非必须）
        refreshLayout.setEnableAutoLoadMore(true);
        // 下拉刷新
        Map<String, Object> map = new HashMap<>();
        map.put("userAccount", CommonUtils.GetUserInfo().getUserAccount());
        map.put("date", binding.tvTitle.getText());
        OKJsonPost(getActivity(), new Gson().toJson(map), getString(R.string.find_daily_cost_by_user_account), new OkSuccessInterface() {
            @Override
            public void OnSuccess(String json) {
                CostRecordStatus status = new Gson().fromJson(json, CostRecordStatus.class);
                if (status.getStatus() != null && status.getStatus().equals("success")) {
                    messageAdapter = new MessageAdapter(getContext(), (List<Map<String, Object>>) status.getData());
                    binding.recyclerviewMessage.setAdapter(messageAdapter);
                } else if (status.getStatus() != null && status.getStatus().equals("error")) {
                    XToastUtils.warning("数据获取失败！");
                }
            }
        });
        refreshLayout.setOnRefreshListener(refreshLayout12 -> refreshLayout12.getLayout().postDelayed(() -> {
            refreshLayout12.finishRefresh();
            refreshLayout12.resetNoMoreData();//setNoMoreData(false);
        }, 500));
        // 触发自动刷新
        refreshLayout.setEnableOverScrollBounce(true);
        refreshLayout.autoRefresh();
        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
        messageAdapter = null;
        linearLayoutManager = null;
    }

    private void listByDay(CalendarDate calendarDate) {
        binding.tvTitle.setText(String.format("%d-%d-%d", calendarDate.year, calendarDate.month, calendarDate.day));
        // 触发自动刷新
        Date newDate = calendarDate.toDate();
        Map<String, Object> map = new HashMap<>();
        map.put("userAccount", CommonUtils.GetUserInfo().getUserAccount());
        map.put("date", new SimpleDateFormat("yyyy-MM-dd").format(newDate));
        OKJsonPost(getActivity(), new Gson().toJson(map), getString(R.string.find_daily_cost_by_user_account), new OkSuccessInterface() {
            @Override
            public void OnSuccess(String json) {
                CostRecordStatus status = new Gson().fromJson(json, CostRecordStatus.class);
                if (status.getStatus() != null && status.getStatus().equals("success")) {
                    MessageAdapter messageAdapter = new MessageAdapter(getContext(), (List<Map<String, Object>>) status.getData());
                    binding.recyclerviewMessage.setAdapter(messageAdapter);
                } else if (status.getStatus() != null && status.getStatus().equals("error")) {
                    XToastUtils.warning("数据获取失败！");
                }
            }
        });
        refreshLayout.autoRefresh();
    }

    private void listByMonth(CalendarDate calendarDate) {
        binding.tvTitle.setText(String.format("%d-%d-%d", calendarDate.year, calendarDate.month, calendarDate.day));
        Date newDate = calendarDate.toDate();
        Map<String, Object> map = new HashMap<>();
        map.put("userAccount", CommonUtils.GetUserInfo().getUserAccount());
        map.put("date", new SimpleDateFormat("yyyy-MM-dd").format(newDate));
        OKJsonPost(getActivity(), new Gson().toJson(map), getString(R.string.find_month_cost_by_user_account), new OkSuccessInterface() {
            @Override
            public void OnSuccess(String json) {
                CostRecordStatus status = new Gson().fromJson(json, CostRecordStatus.class);
                if (status.getStatus() != null && status.getStatus().equals("success")) {
                    MessageAdapter messageAdapter = new MessageAdapter(getContext(), (List<Map<String, Object>>) status.getData());
                    binding.recyclerviewMessage.setAdapter(messageAdapter);
                } else if (status.getStatus() != null && status.getStatus().equals("error")) {
                    XToastUtils.warning("数据获取失败！");
                }
            }
        });
    }
}
